﻿using Bing.Maps;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236

namespace CrmField.Win8App.UserControls
{
    public sealed partial class MapsViewer : UserControl
    {
        private Pushpin _pushpin = null;

        public static readonly DependencyProperty AddressProperty =
            DependencyProperty.Register(
            "Address",
            typeof(String),
            typeof(MapsViewer),
            new PropertyMetadata(null, ChangeAddress)
            );

        public string Address
        {
            get
            {
                return (string)GetValue(AddressProperty);
            }
            set
            {
                SetValue(AddressProperty, (string)value);
            }
        }

        public MapsViewer()
        {
            this.InitializeComponent();
        }

        private static void ChangeAddress(DependencyObject source, DependencyPropertyChangedEventArgs e) 
        {
            (source as MapsViewer).UpdateMap(e.NewValue.ToString()); 
        } 

        private async void UpdateMap(string address)
        {
            if (string.IsNullOrEmpty(address))
                return;

            if (!App.IsInternetAvailable())
                return;

            try
            {

                //Create a request  
                Maps.GeocodeRequest geocodeRequest = new Maps.GeocodeRequest();
                //set credentials  
                geocodeRequest.Credentials = new Maps.Credentials();
                geocodeRequest.Credentials.ApplicationId = App.Current.Resources["BingMapsApiKey"] as string;
                //set address   
                geocodeRequest.Query = address;
                //set confidence level: only results of high confidence  
                Maps.ConfidenceFilter filter = new Maps.ConfidenceFilter();
                filter.MinimumConfidence = Maps.Confidence.Medium;
                //make the request  
                Maps.GeocodeServiceClient geocodeService =
                new Maps.GeocodeServiceClient(Maps.GeocodeServiceClient.EndpointConfiguration.BasicHttpBinding_IGeocodeService);
                Maps.GeocodeResponse geocodeResponse = await geocodeService.GeocodeAsync(geocodeRequest);
                if (geocodeResponse.Results.Count > 0)
                {
                    Bing.Maps.Location loc = new Bing.Maps.Location();
                    loc.Latitude = geocodeResponse.Results[0].Locations[0].Latitude;
                    loc.Longitude = geocodeResponse.Results[0].Locations[0].Longitude;
                    this.map.SetView(loc, 13);

                    if (_pushpin != null)
                        this.map.Children.Remove(_pushpin);

                    _pushpin = new Pushpin();
                    MapLayer.SetPosition(_pushpin, loc);
                    this.map.Children.Add(_pushpin);
                }
            }
            catch (Exception)
            {
                //Could not load map
            }
        }
    }
}
